package com.example.erp.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.example.erp.entity.Admin;
import com.example.erp.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/erp/admin")
@CrossOrigin
public class AdminController {
    @Autowired
    private IAdminService adminService;

//    http://localhost:8088/admin/register?name=admin&password=123456
    @RequestMapping("/register")
    public SaResult register(String name, String password){
        StpUtil.logout();
        if(adminService.checkUsername(name))return SaResult.error("用户名已存在");
        else adminService.register(name,password);
        return SaResult.ok("注册成功");
    }

//    http://localhost:8088/admin/doLogin?name=admin&password=123456
    @RequestMapping("/doLogin")
    public SaResult doLogin(@RequestBody Admin admin) {
        int id=adminService.doLogin(admin.getName(),admin.getPassword());
        if(id>0){
            StpUtil.login(id);
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            System.out.print(tokenInfo);
            // 第3步，返回给前端
            return SaResult.data(tokenInfo);
        }
        return SaResult.error("登录失败");
    }

    @RequestMapping("/isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    @RequestMapping("/tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @RequestMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
}
